home *** CD-ROM | disk | FTP | other *** search
- Path: io.org!singhr
- From: singhr@io.org (Robert Harold Singh)
- Newsgroups: comp.lang.c
- Subject: Re: infix to postfix ???
- Date: 2 Jan 1996 05:47:59 GMT
- Organization: Internex Online, Toronto, Ontario, Canada (416 363 3783)
- Message-ID: <4caguf$1nl@ionews.io.org>
- References: <4b8gve$mu0@db.csie.ncu.edu.tw>
- NNTP-Posting-Host: twirl.io.org
- X-Newsreader: TIN [version 1.2 PL2ovr]
-
- 83085400 (wzyang@csie.ncu.edu.tw) wrote:
-
-
- : Can you help me debug the program ? I need you help !
- : inupt : input a infix contain {} [] () parentheses
- : output : use stack calculate postfix value
- : exampleíG 2*(4+3*2-5)
-
- Here's a program I wrote the other day that converts an infix string at
- argv[1] to postfix notation..
-
- Actually, I think the way I did it is called reverse postfix notation.
- Damn school is always switching terminology on me.
-
- The program may have a few bugs, but hell.. it's my third C program :)
- Btw.. your program is WAAAAY complex than it need be.
-
- /*
-
- infix -> postfix notation converter
-
- */
-
- #include <stdio.h>
- #include <string.h>
-
- main (int argc, char **argv)
- {
- if (argc != 2)
- {
- puts ("usage: postfix infix_equation");
- return 1;
- }
- char *oper = "(+-*/^";
- char *doh = ")";
- int c, i, j, sp, prio[] = {0, 1, 1, 2, 2, 3};
- char output[20];
- /*
- allocate memory for our stacks by parsing argv[1] and tallying
- the number of operators in the string
- */
- for (c = i = sp = 0; unsigned(i) <= strlen (argv[1]); i++)
- {
- j = 0;
- while ((argv[1][i] != oper[j]) && (unsigned(j) < strlen (oper)))
- j++;
- if (argv[1][i] == oper[j])
- c++;
- }
- char ssOper[c], ssPrio[c];
-
- for (i = c = 0; unsigned(i) < strlen (argv[1]); i++)
- {
- j = 0;
- while ((argv[1][i] != oper[j]) && (unsigned(j) < strlen (oper)))
- j++;
- if ((unsigned(j) >= strlen (oper)) && (argv[1][i] != doh[0]))
- {
- output[c] = argv[1][i];
- c++;
- }
- else if (argv[1][i] != doh[0])
- {
- while ((sp >= 0) && (ssPrio[sp] >= prio[j]) && (j > 0))
- {
- output[c] = ssOper[sp];
- sp--;
- c++;
- }
- if ((j == 0) || (sp == -1) || (ssPrio[sp] < prio[j]))
- {
- sp++;
- ssOper[sp] = oper[j];
- ssPrio[sp] = prio[j];
- }
- }
- else
- while ((sp >= 0) && (ssOper[sp] != oper[0]))
- {
- output[c] = ssOper[sp];
- c++;
- sp--;
- }
- }
- while (sp > 0)
- {
- if (ssOper[sp] != oper[0])
- {
- output[c] = ssOper[sp];
- c++;
- }
- sp--;
- }
- output[c] = 0;
- printf ("infix: %s, postfix: %s\n", argv[1], output);
- }
-
- -- Robert H Singh
- singhr@io.org
-